
class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class demo8 {
    public void reorderList(ListNode head) {
        if(head.next == null) {
            return;
        }
        //先找到链表的中间节点
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        //反转后面那个链表
        ListNode headNext = reverseList(slow.next);
        slow.next = null;
        //分别插入虚拟头节点
        ListNode dummy = new ListNode();
        ListNode cur = dummy;
        while(head != null && headNext != null) {
            cur.next = head;
            cur = cur.next;
            head = head.next;
            cur.next = headNext;
            cur = cur.next;
            headNext = headNext.next;
        }
        if(head != null) {
            cur.next = head;
        }
        if(headNext != null) {
            cur.next = headNext;
        }
        head = dummy.next;
    }

    //2.链表逆序
    private ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode prev = head;
        ListNode cur = head.next;
        while(cur != null) {
            ListNode curNext = cur.next;
            cur.next = prev;
            prev = cur;
            cur = curNext;
        }
        head.next = null;
        return prev;
    }

}

class Main {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode cur = head;
        cur.next = new ListNode(2);
        cur = cur.next;
        cur.next = new ListNode(3);
        cur = cur.next;
        cur.next = new ListNode(4);
        cur = cur.next;
        cur.next = new ListNode(5);

        demo8 demo8 = new demo8();
        demo8.reorderList(head);
    }
}